package com.group.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.group.dao.TbRoleMenuMapper;
import com.group.pojo.Common;
import com.group.pojo.TbMenu;
import com.group.pojo.TbRoleMenu;
import com.group.pojo.TbRoleMenuExample;
import com.group.pojo.TbRoleMenuExample.Criteria;
import com.group.pojo.TbUser;
import com.group.pojo.TbUserRole;
import com.group.service.CommonService;
import com.group.service.MenuService;
import com.group.service.RoleMenuService;
import com.group.service.UserRoleService;
import com.group.util.CommonUtil;

@Service
public class RoleMenuServiceImpl implements RoleMenuService{

	@Autowired
	private TbRoleMenuMapper roleMenuMapper;
	@Autowired
	private CommonService commonService;
	@Autowired
	private UserRoleService userRoleService;
	@Autowired
	private MenuService menuService;
	
	
	@Override
	public Map<String, String> save(List<TbRoleMenu> roleMenus, HttpServletRequest request) {
		Map<String, String> returnMap = CommonUtil.getReturnMap("success", "false");
		
		//先清除原有权限
		clearRoleMenu(roleMenus.get(0));
		
		TbUser user = (TbUser) request.getSession().getAttribute("USER_SESSION");
		
		
		int insertCounts = 0;
		for (TbRoleMenu roleMenu : roleMenus) {
			String nextId = commonService.getTbCurrentDateNextId(new Common("tb_role_menu", CommonUtil.getCurrentDate("yyyyMMdd")));
			roleMenu.setId(nextId);
			roleMenu.setCreateUserId(user.getId());
			roleMenu.setCreateTime(new Date());
			roleMenu.setRoleMenuStatus("1");
			int insert = roleMenuMapper.insert(roleMenu);
			insertCounts += insert;
		}
		if (insertCounts == roleMenus.size()) {
			returnMap.put("success", "true");
		}
		return returnMap;
	}
	@Override
	public List<TbRoleMenu> query(TbRoleMenu roleMenu) {
		TbRoleMenuExample example = new TbRoleMenuExample();
		setCondition(example.createCriteria(), roleMenu);
		List<TbRoleMenu> selectByExample = roleMenuMapper.selectByExample(example);
		return selectByExample;
	}
	
	public String clearRoleMenu(TbRoleMenu roleMenu) {
		TbRoleMenuExample example = new TbRoleMenuExample();
		setCondition(example.createCriteria(), roleMenu);
		int deleteByExample = roleMenuMapper.deleteByExample(example);
		if (deleteByExample != 0) {
			return "true";
		}
		return "false";
	}
	private void setCondition(Criteria criteria, TbRoleMenu roleMenu) {
		String roleId = roleMenu.getRoleId();
		if (roleId != null && !"".equals(roleId)) {
			criteria.andRoleIdEqualTo(roleId);
		}
		
		String id = roleMenu.getId();
		if (id != null && !"".equals(id)) {
			criteria.andIdEqualTo(id);
		}
	}
	
	/**
	 * 通过角色得到其所有权限
	 */
	public List<TbMenu> getTbMenusByRoleId(String roleId) {
		List<TbMenu> aloneRoleMenus = roleMenuMapper.getTbMenusByRoleId(roleId);
		return aloneRoleMenus;
	}
	
	@Override
	public List<TbMenu> getUserMenuTreeByUserId(String userId) {
		
		//首先要查询userId所拥有的角色
		TbUserRole userRole = new TbUserRole();
		userRole.setUserId(userId);
		List<TbUserRole> userRoles = userRoleService.getUserRoles(userRole);
		
		//得到所有角色的各自拥有权限
		List<TbMenu> menus = new ArrayList<TbMenu>();
		for (TbUserRole ur : userRoles) {
			String roleId = ur.getRoleId();
			List<TbMenu> aloneRoleMenus = getTbMenusByRoleId(roleId);
			menus.addAll(aloneRoleMenus);
		}
		
		//多个角色的权限可能有重复的权限
		menus = removeRepeat(menus);
		
		//按照启动排序menuOrder进行排序
		menus = menuService.sortMenuAsOrder(menus);
		
		
		//得到树结构
		List<TbMenu> result = getMenuTree(menus, "-1");
		return result;
	}
	
	
	private List<TbMenu> removeRepeat(List<TbMenu> menus) {
		for ( int i = 0; i < menus.size()-1; i++) {
			for (int j = menus.size() -1; j > i; j--) {
				if (menus.get(j).getId().equals(menus.get(i).getId())) {
					menus.remove(j);
				}
			}
		}
		return menus;
	}
	private List<TbMenu> getMenuTree(List<TbMenu> menus, String pid) {
		
		List<TbMenu> result = new LinkedList<TbMenu>();
		for (int i = 0; i < menus.size(); i++) {
			TbMenu node = menus.get(i);
			String nodePid = node.getParentMenuId();
			if ( pid.equals(nodePid) ) {
				
				List<TbMenu> list = getMenuTree(menus, node.getId());
				if (list.size() > 0) {
					node.setSubMenus(list);
				}
				result.add(node);
			}
		}
		return result;
	}
	

	

}